/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "Application.h"
#include "InputSystem.h"
#include "GameWorld.h"

namespace OgreCamNav
{
	Application::Application(void)
	{
	}

	Application::~Application(void)
	{
	}

	
	void Application::init()
	{
		_root=new Ogre::Root();
		_root->showConfigDialog();
		_win=_root->initialise(true,"OgreCamNav");

		defineResource();

		InputSystem::getSingleton().init(_win);
		GameWorld::getSingleton().init(_win);

		lastTime=timer.getMilliseconds();
	}

	//The resource that the whole system need
	void Application::defineResource()
	{
		Ogre::ConfigFile cf;
		cf.load("resources.cfg");
		Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

		Ogre::String secName, typeName, archName;
		while(seci.hasMoreElements()){
			secName = seci.peekNextKey();
			Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
			Ogre::ConfigFile::SettingsMultiMap::iterator i;
			for(i = settings->begin(); i != settings->end(); ++i){
				typeName = i->first;
				archName = i->second;
				Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
			}
		}

		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	}

	void Application::start()
	{
		_running=true;
		while(_running){
			update();//in update we can change running state to false
		}
	}

	void Application::update()
	{
		Ogre::Real deltaT=(timer.getMilliseconds()-lastTime)/1000.0f;
		lastTime=timer.getMilliseconds();

		GameWorld::getSingleton().update(deltaT);
		InputSystem::getSingleton().capture();

		_root->renderOneFrame();	
	}

	void Application::shutdown()
	{
		_running=false;
	}
}
